// 设置公共路径
let baseUrl = 'http://127.0.0.1:3002'
//let baseUrl = 'https://ruanjian211.top:3002'

type Method = 'GET' | 'POST' | 'PUT' | 'DELETE'

interface Options {
  hideLoading?: boolean
  defaultRetryNumber?: number
  env?: 'dev' | 'prod'
}

interface Config {
  path: string
  method: Method
  data?: any
  header?: any
  options?: Options
  retryCount?: number
}

export const request = (config: Config, number = 0): Promise<any> => {
  return new Promise((resolve, reject) => {
    config.header = {
      satoken:
        'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiIzIiwicm5TdHIiOiJVUUZWVWRxT0x5VmJIdWhKVThHYU5YT2pPaVdhY01rZiIsInVzZXJJZCI6IjMiLCJ1c2VyTmFtZSI6IjE4MDY4MzkyMTAifQ.UhAiB8PqP1P3cSJuEEwfkwbXaCRthF-Ldj3yzcCf1t8',
    }

    const defaultOptions = {
      hideLoading: false,
      defaultRetryNumber: 3,
      env: 'prod',
      ...config.options,
    }

    baseUrl = defaultOptions.env === 'dev' ? 'http://127.0.0.1:3002' : baseUrl

    let reqNumber = number

    if (defaultOptions.hideLoading) {
      uni.showLoading({
        title: '加载中....',
      })
    }

    const aa = setTimeout(() => {
      uni.hideLoading()
      uni.showToast({
        title: '加载超时...',
        icon: 'error',
      })
    }, 3000)

    const { path, data, header, method, options } = config

    uni.request({
      url: baseUrl + path,
      data: data,
      header: header,
      method: method,
      success: (response) => {
        const result = response.data
        if (response.statusCode != 200) {
          reqNumber++
          if (reqNumber <= defaultOptions.defaultRetryNumber) {
            console.log(`重试${reqNumber}`)
            request(config, reqNumber)
          }
        }

        uni.hideLoading()
        clearTimeout(aa)
        resolve(result)
      },
      fail: (res) => {
        reqNumber++
        if (reqNumber <= defaultOptions.defaultRetryNumber) {
          console.log(`重试${reqNumber}`)

          request(config, reqNumber)
        }

        if (!defaultOptions.hideLoading) {
          uni.hideLoading()
        }
        clearTimeout(aa)
        uni.showToast({
          title: '请求失败，请重试',
          icon: 'none',
          duration: 1500,
        })
        console.log(res, 'q')

        reject(res)
      },
    })
  })
}
